package com.hao.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class BaseDao {


    static String url = "jdbc:mysql://127.0.0.1:3306/purifier?useUnicode=true&characterEncoding=UTF-8";
    static String user = "root";
    static String pwd = "123";
    static String jdbc = "com.mysql.jdbc.Driver";

    static {
        try {
            Class.forName(jdbc);
        } catch (ClassNotFoundException e) {
            // TODO: handle exception
            System.err.println("驱动加载失败");
            e.printStackTrace();
        }
    }
    public static  Connection getConnection(){

        Connection conn=null;
        try {
            conn=DriverManager.getConnection(url,user,pwd);
        } catch (Exception e) {
            // TODO: handle exception
            System.err.println("连接失败");
            e.printStackTrace();
        }
        return conn;
    }
    public static void  closeConnection(Connection conn,Statement state,ResultSet rs ){
        try {
            if(rs!=null)
                rs.close();
            if (state != null)
                state.close();
            if (conn != null)
                conn.close();

        } catch (Exception e) {
            // TODO: handle exception
            System.err.println("关闭失败");
            e.printStackTrace();
        }
    }
    public static int Update(String sql, Object[] ob) {
        int i = 0;
        Connection conn = null;
        PreparedStatement state = null;
        conn = BaseDao.getConnection();
        try {
            state = conn.prepareStatement(sql);
            for (int j = 0; j < ob.length; j++) {
                state.setObject(j + 1, ob[j]);
            }
            i = state.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            BaseDao.closeConnection(conn, state, null);
        }
        return i;
    }
}
